﻿using System;
using System.Collections.Generic;
using System.Linq;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using System.Data;

namespace YJY_DMZS.SupplyChain
{
    public partial class FrmSalesOrder : XtraForm
    {
        /// <summary>
        /// 单据ID,非零为修改单据
        /// </summary>
        /// <param name="ID"></param>
        public FrmSalesOrder(long ID)
            : this()
        {
            this.ID = ID;
        }

        public FrmSalesOrder()
        {
            InitializeComponent();
            InitGrid();
        }

        /// <summary>
        /// 初始网格显示
        /// </summary>
        private void InitGrid()
        {
            grvBody.IndicatorWidth = grvBody.IndicatorWidth == -1 ? 40 : grvBody.IndicatorWidth;
            grvBody.OptionsView.ShowIndicator = true;

            CommonControl.DxGridHelper.InitGridStyle(grvBody);
        }

        private DMZS.Model.DlyndxOrder.OrderType OrderType;
        public long ID;

        private int DepartmentID;
        private string DepartmentCode;
        private string DepartmentName;

        private int ClientID;
        private string ClientCode;
        private string ClientName;

        private int WarehouseID;
        private string WarehouseCode;
        private string WarehouseName;


        private void FrmPurchaseOrder_Load(object sender, EventArgs e)
        {
            this.OrderType = DMZS.Model.DlyndxOrder.OrderType.XSDD;

            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            var bll = new DMZS.BLL.SalesOrder();
            var row = bll.GetHead(ID);

            if (row != null)
            {
                DepartmentID = Convert.ToInt32(row["deptid"]);
                DepartmentCode = row["DepartmentCode"].ToString();
                DepartmentName = row["DepartmentName"].ToString();
                ClientID = row["btypeid"].ToString() == string.Empty ? 0 : Convert.ToInt32(row["btypeid"]);
                ClientCode = row["ClientCode"].ToString();
                ClientName = row["ClientName"].ToString();
                WarehouseID = row["ktypeid"].ToString() == string.Empty ? 0 : Convert.ToInt32(row["ktypeid"]);
                WarehouseCode = row["WarehouseCode"].ToString();
                WarehouseName = row["WarehouseName"].ToString();

                txtCode.Text = row["Number"].ToString();
                txtOperator.Text = row["InputNo"].ToString();
                bteDepartment.Text = DepartmentName;
                bteClient.Text = ClientName;
                if (row["todate"] == DBNull.Value)
                {
                    datToDate.Text = string.Empty;
                }
                else
                {
                    datToDate.DateTime = Convert.ToDateTime(row["todate"]);
                }
                bteWarehouse.Text = WarehouseName;
                txtChecker.Text = row["checke"].ToString();
                txtCreateTime.Text = string.Format("{0:yyyy-MM-dd hh:mm:ss}", row["Date"]);
                txtCheckTime.Text = row["checkeDate"] == null ? "" : string.Format("{0:yyyy-MM-dd hh:mm:ss}", row["checkeDate"]);

                RefreshEnabled(Convert.ToInt32(row["draft"]));

                var dt = bll.GetBody(ID);
                if (dt != null)
                {
                    grdBody.DataSource = dt;
                }
                else
                {
                    pnlTools.Enabled = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                    XtraMessageBox.Show("加载表体失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                XtraMessageBox.Show("加载表头失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }

        /// <summary>
        /// 新记录
        /// </summary>
        private void NewRecord()
        {
            if (!LoadNewCode())
            {
                return;
            }
            InitNew();

            bteDepartment.Focus();
        }
        /// <summary>
        /// 初始新记录
        /// </summary>
        private void InitNew()
        {
            ID = 0;
            DepartmentID = 0;
            DepartmentCode = string.Empty;
            DepartmentName = string.Empty;
            ClientID = 0;
            ClientCode = string.Empty;
            ClientName = string.Empty;
            WarehouseID = 0;
            WarehouseCode = string.Empty;
            WarehouseName = string.Empty;

            txtOperator.Text = string.Empty;
            bteDepartment.Text = string.Empty;
            bteClient.Text = string.Empty;
            datToDate.Text = string.Empty;
            bteWarehouse.Text = string.Empty;
            txtChecker.Text = string.Empty;
            mmoRemark.Text = string.Empty;
            txtCreateTime.Text = "";
            txtCheckTime.Text = "";

            RefreshEnabled(-1);


            var bll = new DMZS.BLL.SalesOrder();
            var dt = bll.GetBody(-1);
            if (dt != null)
            {
                grdBody.DataSource = dt;
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                XtraMessageBox.Show("加载表体失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }

            bteDepartment.Properties.Buttons[0].Enabled = true;
            bteClient.Properties.Buttons[0].Enabled = true;
            bteWarehouse.Properties.Buttons[0].Enabled = true;
        }

        /// <summary>
        /// 刷新功能可用性
        /// </summary>
        /// <param name="status">-1:草稿;0:待审;1:已审;2:关闭</param>
        private void RefreshEnabled(int status)
        {
            switch (status)
            {
                case 0:
                    btnSave.Enabled = true;
                    btnDelete.Enabled = true;
                    btnCheck.Enabled = true;
                    btnUnCheck.Enabled = false;
                    btnClose.Enabled = false;

                    txtOperator.Properties.ReadOnly = false;
                    bteDepartment.Properties.ReadOnly = false;
                    bteDepartment.Properties.Buttons[0].Enabled = true;
                    bteClient.Properties.ReadOnly = false;
                    bteClient.Properties.Buttons[0].Enabled = true;
                    datToDate.Properties.ReadOnly = false;
                    bteWarehouse.Properties.ReadOnly = false;
                    bteWarehouse.Properties.Buttons[0].Enabled = true;
                    mmoRemark.Properties.ReadOnly = false;
                    txtCreator.Properties.ReadOnly = true;
                    txtChecker.Properties.ReadOnly = false;

                    grvBody.OptionsBehavior.Editable = true;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

                    lblStatus.Text = "待审";
                    break;
                case 1:
                    btnSave.Enabled = false;
                    btnDelete.Enabled = false;
                    btnCheck.Enabled = false;
                    btnUnCheck.Enabled = true;
                    btnClose.Enabled = true;

                    txtOperator.Properties.ReadOnly = true;
                    bteDepartment.Properties.ReadOnly = true;
                    bteDepartment.Properties.Buttons[0].Enabled = false;
                    bteClient.Properties.ReadOnly = true;
                    bteClient.Properties.Buttons[0].Enabled = false;
                    datToDate.Properties.ReadOnly = true;
                    bteWarehouse.Properties.ReadOnly = true;
                    bteWarehouse.Properties.Buttons[0].Enabled = false;
                    mmoRemark.Properties.ReadOnly = true;
                    txtCreator.Properties.ReadOnly = true;
                    txtChecker.Properties.ReadOnly = true;

                    grvBody.OptionsBehavior.Editable = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

                    lblStatus.Text = "已审";
                    break;
                case 2:
                    btnSave.Enabled = false;
                    btnDelete.Enabled = false;
                    btnCheck.Enabled = false;
                    btnUnCheck.Enabled = false;
                    btnClose.Enabled = false;

                    txtOperator.Properties.ReadOnly = true;
                    bteDepartment.Properties.ReadOnly = true;
                    bteDepartment.Properties.Buttons[0].Enabled = false;
                    bteClient.Properties.ReadOnly = true;
                    bteClient.Properties.Buttons[0].Enabled = false;
                    datToDate.Properties.ReadOnly = true;
                    bteWarehouse.Properties.ReadOnly = true;
                    bteWarehouse.Properties.Buttons[0].Enabled = false;
                    mmoRemark.Properties.ReadOnly = true;
                    txtCreator.Properties.ReadOnly = true;
                    txtChecker.Properties.ReadOnly = true;

                    grvBody.OptionsBehavior.Editable = false;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

                    lblStatus.Text = "已关闭";
                    break;
                default:
                    btnSave.Enabled = true;
                    btnDelete.Enabled = false;
                    btnCheck.Enabled = false;
                    btnUnCheck.Enabled = false;
                    btnClose.Enabled = false;

                    txtOperator.Properties.ReadOnly = false;
                    bteDepartment.Properties.ReadOnly = false;
                    bteDepartment.Properties.Buttons[0].Enabled = true;
                    bteClient.Properties.ReadOnly = false;
                    bteClient.Properties.Buttons[0].Enabled = true;
                    datToDate.Properties.ReadOnly = false;
                    bteWarehouse.Properties.ReadOnly = false;
                    bteWarehouse.Properties.Buttons[0].Enabled = true;
                    mmoRemark.Properties.ReadOnly = false;
                    txtCreator.Properties.ReadOnly = false;
                    txtChecker.Properties.ReadOnly = true;

                    grvBody.OptionsBehavior.Editable = true;
                    grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

                    lblStatus.Text = "草稿";
                    break;
            }
        }

        /// <summary>
        /// 加载编号
        /// </summary>
        /// <returns></returns>
        private bool LoadNewCode()
        {
            string code;
            do
            {
                code = Common.Common.GetOrderCode(OrderType);
                if (code != null)
                {
                    break;
                }
            }
            while (DialogResult.Yes == XtraMessageBox.Show("获取单据编号失败\r重新获取（若多次失败，请联系管理员）？", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2));

            if (code != null)
            {
                txtCode.Text = code;
                return true;
            }
            else
            {
                pnlTools.Enabled = false;
                grvBody.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                return false;
            }
        }

        private void repUnitBaseCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmUnitBase_dlg frmUnitBase_dlg = new DialogForm.FrmUnitBase_dlg();
            frmUnitBase_dlg.MultiSelect = false;
            frmUnitBase_dlg.ReturnList += new DialogForm.FrmUnitBase_dlg.ReturnListEventHandler(frmUnitBase_dlg_ReturnList);
            frmUnitBase_dlg.ShowDialog();
        }

        void frmUnitBase_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            grvBody.SetFocusedRowCellValue("unit", lists[0]["UnitBaseID"]);
            grvBody.SetFocusedRowCellValue("UnitBaseCode", lists[0]["BaseCode"]);
            grvBody.SetFocusedRowCellValue("UnitBaseName", lists[0]["BaseName"]);
        }

        private void repProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmProduct_dlg frmProduct_dlg = new DialogForm.FrmProduct_dlg();
            frmProduct_dlg.MultiSelect = true;
            frmProduct_dlg.ReturnList += new DialogForm.FrmProduct_dlg.ReturnListEventHandler(frmProduct_dlg_ReturnList);

            grvBody.ValidateRow -= new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(grvBody_ValidateRow);
            grvBody.ValidatingEditor -= new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(grvBody_ValidatingEditor);

            frmProduct_dlg.ShowDialog();

            grvBody.ValidateRow += new DevExpress.XtraGrid.Views.Base.ValidateRowEventHandler(grvBody_ValidateRow);
            grvBody.ValidatingEditor += new DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventHandler(grvBody_ValidatingEditor);

        }

        void frmProduct_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            foreach (DataRow row in lists.ToArray())
            {
                int i = 0;
                DataTable dt = (grdBody.DataSource as DataTable);
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["ProductID"].ToString() == row["ID"].ToString())
                    {
                        //int orderTypeID = grvBody.GetRowCellValue(i, "OrderType") == DBNull.Value ? 0 : Convert.ToInt32(grvBody.GetRowCellValue(i, "OrderType"));
                        //if (Convert.ToInt32(BarcodeInfo["OrderTypeID"]) != orderTypeID)
                        //{
                        //    htb["ID"] = -1;
                        //    htb["Message"] = "当前版本不支持一张单子下有不同来源的相同产品";
                        //    return;
                        //}
                        //else
                        //{
                        //    object obj = grvBody.GetRowCellValue(i, "Qty");
                        //    int newVariable = obj == DBNull.Value ? 0 : Convert.ToInt32(obj);
                        //    grvBody.SetRowCellValue(i, "Qty", newVariable + 1);
                        //}
                        break;
                    }
                }

                if (i == dt.Rows.Count)
                {
                    if (grvBody.GetFocusedRowCellValue("PtypeId") == null
                        || grvBody.GetFocusedRowCellValue("PtypeId") == DBNull.Value
                        || grvBody.GetFocusedRowCellValue("PtypeId").ToString() != row["ID"].ToString())
                    {
                        grvBody.AddNewRow();
                        grvBody.SetFocusedRowCellValue("PtypeId", row["ID"]);
                        grvBody.SetFocusedRowCellValue("ProductCode", row["Code"]);
                        grvBody.SetFocusedRowCellValue("ProductName", row["Name"]);
                        grvBody.SetFocusedRowCellValue("Qty", 1);
                        grvBody.SetFocusedRowCellValue("unit", row["UnitID"]);
                        grvBody.SetFocusedRowCellValue("UnitBaseCode", row["BaseCode"]);
                        grvBody.SetFocusedRowCellValue("UnitBaseName", row["BaseName"]);
                        grvBody.SetFocusedRowCellValue("OrderType", 0);
                        grvBody.SetFocusedRowCellValue("OrderCode", 0);
                        grvBody.SetFocusedRowCellValue("OrderNumber", "");
                        grvBody.SetFocusedRowCellValue("OrderDlyCode", 0);
                        grvBody.SetFocusedRowCellValue("OrderTypeName", "");

                        grvBody.UpdateCurrentRow();
                    }
                }

            }
        }

        private void bteDepartment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmDepartment_dlg frmDepartment_dlg = new DialogForm.FrmDepartment_dlg();
            frmDepartment_dlg.ReturnList += new DialogForm.FrmDepartment_dlg.ReturnListEventHandler(frmDepartment_dlg_ReturnList);
            frmDepartment_dlg.ShowDialog();
        }

        void frmDepartment_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists == null) return;

            DepartmentID = Convert.ToInt32(lists[0]["ID"]);
            DepartmentCode = lists[0]["Code"].ToString();
            DepartmentName = lists[0]["Name"].ToString();
            bteDepartment.Text = DepartmentCode;
        }

        private void bteDepartment_Enter(object sender, EventArgs e)
        {
            if (DepartmentCode != string.Empty)
            {
                bteDepartment.Text = DepartmentCode;
            }
        }

        private void bteDepartment_Leave(object sender, EventArgs e)
        {
            bteDepartment.Text = DepartmentName;
        }

        /// <summary>
        /// 验证部门
        /// </summary>
        /// <returns></returns>
        private bool ValidateDept()
        {
            if (bteDepartment.Text.Trim().Length == 0)
            {
                DepartmentID = 0;
                DepartmentName = string.Empty;
                DepartmentCode = string.Empty;
                return true;
            }

            if (bteDepartment.Text.Trim() == DepartmentCode)
            {
                bteDepartment.Text = DepartmentName;
                return true;
            }

            var bll = new DMZS.BLL.DepartmentNew();
            var row = bll.GetRecordByCode(bteDepartment.Text.Trim());
            if (row != null)
            {
                DepartmentID = Convert.ToInt32(row["ID"]);
                DepartmentCode = row["Code"].ToString();
                DepartmentName = row["Name"].ToString();
                bteDepartment.Text = DepartmentName;
                return true;
            }
            else
            {
                DepartmentID = 0;
                DepartmentCode = string.Empty;
                DepartmentName = string.Empty;
                return false;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            btnSave.Focus();

            if (DepartmentID == 0)
            {
                XtraMessageBox.Show("请输入采购部门。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteDepartment.Focus();
                return;
            }
            else if (ClientID == 0)
            {
                XtraMessageBox.Show("请输入供应商。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteClient.Focus();
                return;
            }
            else if ((grdBody.DataSource as DataTable).Rows.Count == 0)
            {
                XtraMessageBox.Show("请填写销售内容。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (txtCreator.Text.Trim().Length == 0)
            {
                XtraMessageBox.Show("请填写建单人。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            for (int i = 0; i < grvBody.RowCount; i++)
            {
                grvBody.FocusedRowHandle = i;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["ProductCode"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;
                view.FocusedColumn = view.Columns["Qty"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;
                if (!view.ValidateEditor()) return;
                view.FocusedColumn = view.Columns["Price"];
                view.FocusedColumn.View.ShowEditor();
                if (!view.ValidateEditor()) return;
            }

            if (ID <= 0)
            {
                SaveNew();
            }
            else
            {
                SaveModify();
            }
        }
        /// <summary>
        /// 保存修改
        /// </summary>
        private void SaveModify()
        {
            var bll = new DMZS.BLL.SalesOrder();
            var model = new DMZS.Model.SalesOrder();

            model.Number = txtCode.Text;
            model.Comment = mmoRemark.Text;
            model.btypeid = ClientID.ToString();
            model.ktypeid = WarehouseID.ToString();
            model.InputNo = txtOperator.Text.Trim();
            model.deptid = DepartmentID.ToString();
            model.todate = datToDate.Text == string.Empty ? DateTime.MinValue : datToDate.DateTime.Date;
            model.Tbody = grdBody.DataSource as DataTable;
            model.Vchcode = ID;

            var result = bll.UpdateExpand(model);

            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -10021)
                {
                    XtraMessageBox.Show("单据类型查找失败，建议关闭选项卡。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10022)
                    {
                        XtraMessageBox.Show("该供应商被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        bteClient.Focus();
                        bteClient.SelectAll();
                    }
                    else
                    {
                        if (result == -10023)
                        {
                            XtraMessageBox.Show("该部门被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            bteClient.Focus();
                            bteClient.SelectAll();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 保存新增
        /// </summary>
        private void SaveNew()
        {
            var bll = new DMZS.BLL.SalesOrder();
            var model = new DMZS.Model.SalesOrder();

            var bllVchtype = new DMZS.BLL.Vchtype();

            model.Date = DateTime.Now;
            model.Number = txtCode.Text;
            model.VchType = bllVchtype.GetOrderTypeID(OrderType);
            model.Comment = mmoRemark.Text;
            model.btypeid = ClientID.ToString();
            model.ktypeid = WarehouseID.ToString();
            model.ifcheck = "0";
            model.checke = string.Empty;
            model.Period = 0;
            model.InputNo = txtOperator.Text.Trim();
            model.draft = 0;
            model.deptid = DepartmentID.ToString();
            model.IsStop = 0;
            model.todate = datToDate.Text == string.Empty ? DateTime.MinValue : datToDate.DateTime.Date;
            model.Tbody = grdBody.DataSource as DataTable;
            model.Creator = txtCreator.Text.Trim();

            var result = bll.AddExpand(model);
            if (result > 0)
            {
                ID = result;
                LoadData();
                XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -10021)
                {
                    XtraMessageBox.Show("单据类型查找失败，建议关闭选项卡。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10022)
                    {
                        XtraMessageBox.Show("该供应商被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        bteClient.Focus();
                        bteClient.SelectAll();
                    }
                    else
                    {
                        if (result == -10023)
                        {
                            XtraMessageBox.Show("该部门被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            bteClient.Focus();
                            bteClient.SelectAll();
                        }
                    }
                }
            }
        }

        private void grvBody_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "Qty" || e.Column.FieldName == "Price")
            {
                decimal qty, price;
                if (grvBody.GetFocusedRowCellValue("Qty") == null
                    || grvBody.GetFocusedRowCellValue("Qty") == DBNull.Value
                    || grvBody.GetFocusedRowCellValue("Qty").ToString() == string.Empty)
                {
                    qty = 0;
                }
                else
                {
                    qty = Convert.ToDecimal(grvBody.GetFocusedRowCellValue("Qty"));
                }

                if (grvBody.GetFocusedRowCellValue("Price") == null
                   || grvBody.GetFocusedRowCellValue("Price") == DBNull.Value
                   || grvBody.GetFocusedRowCellValue("Price").ToString() == string.Empty)
                {
                    price = 0;
                }
                else
                {
                    price = Convert.ToDecimal(grvBody.GetFocusedRowCellValue("Price"));
                }

                grvBody.SetRowCellValue(e.RowHandle, "SubTotal", qty * price);
            }
        }

        private void grvBody_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            switch (grvBody.FocusedColumn.FieldName)
            {
                case "ProductCode":
                    var code = e.Value;
                    if (code == null || code.ToString().Trim().Length == 0)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "PtypeId", 0);
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "ProductName", "");
                        return;
                    }
                    var bll = new DMZS.BLL.Product();
                    var row = bll.GetRecordByCode(code.ToString().Trim());
                    if (row != null)
                    {
                        var dt = grdBody.DataSource as DataTable;
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            if (grvBody.FocusedRowHandle != grvBody.GetRowHandle(i))
                            {
                                if (dt.Rows[i]["ProductCode"].ToString().Trim() == row["Code"].ToString())
                                {
                                    e.ErrorText = "编号重复";
                                    e.Valid = false;
                                    return;
                                }
                            }
                        }

                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "PtypeId", Convert.ToInt64(row["ID"].ToString()));
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "ProductName", row["Name"].ToString());
                    }
                    else
                    {
                        e.ErrorText = "该产品编号不存在";
                        e.Valid = false;
                        return;
                    }
                    e.Value = row["Code"].ToString();
                    break;

                case "Qty":
                    var qty = e.Value;
                    if (qty == null || Convert.ToInt32(qty) <= 0)
                    {
                        e.ErrorText = "请输入正确数量";
                        e.Valid = false;
                    }
                    break;

                case "Price":
                    var price = e.Value;
                    if (price == null || Convert.ToDecimal(price) < 0)
                    {
                        e.ErrorText = "请输入正确价格";
                        e.Valid = false;
                    }
                    break;
                case "UnitBaseCode":
                    var value = e.Value;
                    if (value == null || value.ToString().Trim().Length == 0)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "unit", 0);
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "UnitBaseName", "");
                        return;
                    }
                    var bll1 = new DMZS.BLL.UnitBase();
                    var row1 = bll1.GetRecordByCode(value.ToString().Trim());
                    if (row1 != null)
                    {
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "unit", Convert.ToInt64(row1["UnitBaseID"].ToString()));
                        grvBody.SetRowCellValue(grvBody.FocusedRowHandle, "UnitBaseName", row1["BaseName"].ToString());
                    }
                    else
                    {
                        e.ErrorText = "该单位编号不存在";
                        e.Valid = false;
                    }
                    e.Value = value.ToString().Trim();
                    break;
            }
        }

        private void grvBody_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            var obj = grvBody.GetRowCellValue(e.RowHandle, "ProductCode");
            if (obj == null || obj.ToString().Trim().Length == 0)
            {
                e.ErrorText = " 请输入产品编号\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["ProductCode"];
                view.FocusedColumn.View.ShowEditor();

                return;
            }
            var qty = grvBody.GetRowCellValue(e.RowHandle, "Qty");
            if (qty.ToString() == string.Empty || Convert.ToInt32(qty) == 0)
            {
                e.ErrorText = " 请输入正确数量\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["Qty"];
                view.FocusedColumn.View.ShowEditor();
                return;
            }
            var price = grvBody.GetRowCellValue(e.RowHandle, "Price");
            if (price.ToString() == string.Empty || Convert.ToDecimal(price) < 0)
            {
                e.ErrorText = " 请输入正确价格\r";
                e.Valid = false;
                var view = grdBody.FocusedView as DevExpress.XtraGrid.Views.Base.ColumnView;
                view.FocusedColumn = view.Columns["Price"];
                view.FocusedColumn.View.ShowEditor();
                return;
            }
        }

        private void grvBody_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.WindowCaption = "输入提示";
        }

        private void grvBody_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
        }



        /// <summary>
        /// 验证供应商
        /// </summary>
        /// <returns></returns>
        private bool ValidateClient()
        {
            if (bteClient.Text.Trim().Length == 0)
            {
                ClientID = 0;
                ClientName = string.Empty;
                ClientCode = string.Empty;
                return true;
            }

            if (bteClient.Text.Trim() == ClientCode)
            {
                bteClient.Text = ClientName;
                return true;
            }

            var bll = new DMZS.BLL.Client();
            var row = bll.GetRecordByCode(bteClient.Text.Trim());
            if (row != null)
            {
                ClientID = Convert.ToInt32(row["ID"]);
                ClientCode = row["Code"].ToString();
                ClientName = row["Name"].ToString();
                bteClient.Text = ClientName;
                return true;
            }
            else
            {
                ClientID = 0;
                ClientName = string.Empty;
                ClientCode = string.Empty;
                return false;
            }
        }

        private void bteWarehouse_Enter(object sender, EventArgs e)
        {
            if (WarehouseCode != string.Empty)
            {
                bteWarehouse.Text = WarehouseCode;
            }
        }

        private void bteWarehouse_Leave(object sender, EventArgs e)
        {
            bteWarehouse.Text = WarehouseName;
        }
        /// <summary>
        /// 验证仓库
        /// </summary>
        /// <returns></returns>
        private bool ValidateWarehouse()
        {
            if (bteWarehouse.Text.Trim().Length == 0)
            {
                WarehouseID = 0;
                WarehouseName = string.Empty;
                WarehouseCode = string.Empty;
                return true;
            }

            if (bteWarehouse.Text.Trim() == WarehouseCode)
            {
                bteWarehouse.Text = WarehouseName;
                return true;
            }

            var bll = new DMZS.BLL.Warehouse();
            var row = bll.GetRecordByCode(bteWarehouse.Text.Trim());
            if (row != null)
            {
                WarehouseID = Convert.ToInt32(row["ID"]);
                WarehouseCode = row["Code"].ToString();
                WarehouseName = row["Name"].ToString();
                bteWarehouse.Text = WarehouseName;
                return true;
            }
            else
            {
                WarehouseID = 0;
                WarehouseName = string.Empty;
                WarehouseCode = string.Empty;
                return false;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                return;
            }
            NewRecord();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                return;
            }
            else
            {
                LoadData();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var frm = new DialogForm.FrmSalesOrder_dlg();
            frm.ReturnID += new DialogForm.FrmSalesOrder_dlg.ReturnIDEventHandler(frm_ReturnID);
            frm.ShowDialog();
        }

        private void frm_ReturnID(long ID)
        {
            this.ID = ID;
            LoadData();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                if (DialogResult.No == XtraMessageBox.Show("确认删除?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    return;
                }

                var bll = new DMZS.BLL.SalesOrder();
                var result = bll.DeleteExpand(ID);
                if (result == -10031)
                {
                    XtraMessageBox.Show("该条记录已被审核，无法删除请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10032)
                    {
                        XtraMessageBox.Show("该条记录已被关闭，无法删除请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        NewRecord();
                    }
                }
            }
        }


        private void bteDepartment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!ValidateDept())
                {
                    XtraMessageBox.Show("不存在该部门编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bteDepartment.Focus();
                    bteDepartment.SelectAll();
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
            }
        }



        private void bteWarehouse_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!ValidateWarehouse())
                {
                    XtraMessageBox.Show("不存在该仓库编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bteWarehouse.Focus();
                    bteWarehouse.SelectAll();
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
            }
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (txtChecker.Text.Trim().Length == 0)
            {
                XtraMessageBox.Show("请输入审核人。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var bll = new DMZS.BLL.SalesOrder();
            var result = bll.Check(ID, txtChecker.Text.Trim());
            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("审核成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -1000)
                {
                    NewRecord();
                    XtraMessageBox.Show("该条记录已被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10001)
                    {
                        XtraMessageBox.Show("该条记录已被其他用户审核，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (result == -1003)
                        {
                            XtraMessageBox.Show("该条记录已被关闭，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show("审核失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }
        private void btnUnCheck_Click(object sender, EventArgs e)
        {
            var bll = new DMZS.BLL.SalesOrder();
            var result = bll.UnCheck(ID);
            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("反审成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -1000)
                {
                    NewRecord();
                    XtraMessageBox.Show("该条记录已被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10002)
                    {
                        XtraMessageBox.Show("该条记录已被其他用户反审核，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (result == -1003)
                        {
                            XtraMessageBox.Show("该条记录已被关闭，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show("反审失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            var bll = new DMZS.BLL.SalesOrder();
            var result = bll.Close(ID);
            if (result > 0)
            {
                LoadData();
                XtraMessageBox.Show("关闭成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (result == -1000)
                {
                    NewRecord();
                    XtraMessageBox.Show("该条记录已被删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (result == -10002)
                    {
                        XtraMessageBox.Show("该条记录已被其他用户反审核，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (result == -1003)
                        {
                            XtraMessageBox.Show("该条记录已被其他用户关闭，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show("关闭失败。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void bteClient_Enter(object sender, EventArgs e)
        {
            if (ClientCode != string.Empty)
            {
                bteClient.Text = ClientCode;
            }
        }

        private void bteClient_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!ValidateClient())
                {
                    XtraMessageBox.Show("不存在该供应商编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bteClient.Focus();
                    bteClient.SelectAll();
                }
                else
                {
                    SendKeys.Send("{TAB}");
                }
            }
        }

        private void bteClient_Leave(object sender, EventArgs e)
        {
            bteClient.Text = ClientName;
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Focus();
            MessageBox.Show("d");
        }

        private void bteClient_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmClient_dlg frmClient_dlg = new DialogForm.FrmClient_dlg();
            frmClient_dlg.ReturnList += new DialogForm.FrmClient_dlg.ReturnListEventHandler(frmClient_dlg_ReturnList);
            frmClient_dlg.ShowDialog();
        }

        void frmClient_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists.Count == 0) return;

            ClientID = Convert.ToInt32(lists[0]["ID"]);
            ClientCode = lists[0]["Code"].ToString();
            ClientName = lists[0]["Name"].ToString();
            bteClient.Text = ClientCode;
        }

        private void bteWarehouse_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmWarehouse_dlg frmWarehouse_dlg = new DialogForm.FrmWarehouse_dlg();
            frmWarehouse_dlg.ReturnList += new DialogForm.FrmWarehouse_dlg.ReturnListEventHandler(frmWarehouse_dlg_ReturnList);
            frmWarehouse_dlg.ShowDialog();
        }

        void frmWarehouse_dlg_ReturnList(List<DataRow> lists)
        {
            if (lists.Count == 0) return;

            WarehouseID = Convert.ToInt32(lists[0]["ID"]);
            WarehouseCode = lists[0]["Code"].ToString();
            WarehouseName = lists[0]["Name"].ToString();
            bteWarehouse.Text = WarehouseCode;
        }

        private void tmiDelete_Click(object sender, EventArgs e)
        {
            int[] selects = grvBody.GetSelectedRows();
            grvBody.DeleteSelectedRows();
            (grdBody.DataSource as DataTable).AcceptChanges();
        }
    }
}
